<template>
  <div class="width-100-per height-100-per" style="z-index: -2" :style="{background:'url(' + loginbg + ')'}">
<!--    <vue-particles-->
<!--      color="#235C46"-->
<!--      :particleOpacity="0.7"-->
<!--      :particlesNumber="60"-->
<!--      shapeType="circle"-->
<!--      :particleSize="4"-->
<!--      linesColor="#fff"-->
<!--      :linesWidth="1"-->
<!--      :lineLinked="true"-->
<!--      :lineOpacity="0.4"-->
<!--      :linesDistance="150"-->
<!--      :moveSpeed="2"-->
<!--      :hoverEffect="true"-->
<!--      hoverMode="grab"-->
<!--      :clickEffect="true"-->
<!--      clickMode="push"-->
<!--      class="lizi"-->
<!--    >-->
<!--    </vue-particles>-->
<!--    <div class="lizi01"></div>-->
    <!--    <div class="bttn"></div>-->
<!--    <div class="height-100-per width-100-per">-->
      <div class="layout-center-top LoginDIV" style="float:right;z-index:999;margin: 10% 15% 0 0">
        <h1 style="margin-top: 15px;">用户登录</h1>
        <div class="LoginDIV-01" style="">
          <div class="LoginDIV-02 layout-center">
            <a-input class="marIn" placeholder="请输入账号" v-model="code">
              <a-icon slot="prefix"  type="user"/>
            </a-input>
            <a-input class="marIn" placeholder="请输入密码" type="password" v-model="password">
              <a-icon slot="prefix"  type="lock"/>
            </a-input>
            <a-button class="LoginButton"  @click="loginIn" :loading="loading">登录</a-button>
            <p><a style="color: #ccc;"@click="registerR">注册</a></p>
          </div>
        </div>
<!--      </div>-->
    </div>
    <a-modal
      title="注册"
      width="600px"
      :visible="modalPersonnel"
      @cancel="cancelPersonnel"
      :footer="footers">
      <template slot="footer">
        <a-button key="back" icon="reload" @click="handleReset">重置</a-button>
        <a-button key="add" icon="check" type="primary" :loading="loadings" @click="addPersonnel">注册提交</a-button>
      </template>
      <div class="width-100-per layout-side">
        <div class="layout-center-top padding-10-px">
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>账户名</div>
            <a-input class="formInput" v-model="userData.name"></a-input>
          </div>
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>编号</div>
            <a-input class="formInput" v-model="userData.code"></a-input>
          </div>
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>上级建制</div>
            <a-tree-select
              class="formInput"
              :value="values"
              :treeData="armyTypesDatas"
              treeDefaultExpandAll
              @select="onSelect"
            />
          </div>
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>身份类别</div>
            <a-select placeholder="" class="formInput" v-model="userData.userType">
              <a-select-option value="999">请选择</a-select-option>
              <a-select-option v-for="(i,index) in userTypeData" :value="i.key" :key="index">{{i.title}}</a-select-option>
            </a-select>
          </div>
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>用户类别</div>
            <a-select placeholder="" class="formInput" v-model="userData.armyType">
              <a-select-option value="999">请选择</a-select-option>
              <a-select-option v-for="(i,index) in armyTypeData" :value="i.key" :key="index">{{i.title}}</a-select-option>
            </a-select>
          </div>
          <div class="layout-side margin-bottom-10-px">
            <div class="formSpan">联系方式</div>
            <a-input class="formInput" v-model="userData.phone" @input="inputPhone" @blur="inPhones"></a-input>
          </div>
        </div>
        <div class="layout-right-top">
          <div class="layout-center-top">
            <a-upload
              name="avatar"
              lisType="picture"
              :showUploadList="false"
              :action="userData.userImg"
              @change="uplodPic"
              accept="image/jpg,image/jpeg,image/png"
            >
              <a-avatar shape="square" icon="user" :size="100" :src="userData.userImg"/>

            </a-upload>
            <div class="layout-side margin-bottom-10-px" style="margin-top: 26px;">
              <div class="formSpan"><span style="color: #f5222d">*&nbsp;</span>身份证号</div>
              <a-input class="formInput" v-model="userData.idCard" @input="inputIdcard" @blur="inCardMessage"></a-input>
            </div>
            <div class="layout-side margin-bottom-10-px">
              <div class="formSpan">性别</div>
              <a-select placeholder="" :disabled="genderDis" class="formInput" v-model="userData.gender">
                <a-select-option value="999">请选择</a-select-option>
                <a-select-option value="0">男</a-select-option>
                <a-select-option value="1">女</a-select-option>
              </a-select>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>
<script>
  import {Input,Button,Icon,Modal,Select,Upload,Avatar,TreeSelect,} from 'ant-design-vue'

  const userTypeData=[
    {key:0,title:'学生',id:'0'},
    {key:1,title:'教师',id:'1'},
    {key:2,title:'员工',id:'2'}
  ]
  const armyTypeData=[
    {key:0,title:'普通用户',id:'0'},
    {key:1,title:'修理工',id:'1'},
    {key:2,title:'管理员',id:'2'}
  ]
  export default {
    components:{
      AInput:Input,
      AIcon:Icon,
      AButton:Button,
      AModal:Modal,
      ASelectOption:Select.Option,
      AUpload:Upload,
      AAvatar:Avatar,
      ATreeSelect:TreeSelect,
      ASelect:Select,

    },
    data(){
      return{
        genderDis:true,
        loginbg:require('../assets/img/bg.jpg'),
        userTypeData,
        armyTypeData,
        loadings:false,
        modalPersonnel:false,
        footers:this.slot,
        loading:false,
        code:"",
        password:"",
        armyTypesDatas:[],
        values:"请选择",
        userData:{
          name:'',
          armyType:'999',
          code:'',
          gender:'0',
          idCard:'',
          password:'123456',
          phone:'',
          userImg:'',
          remark:'0',
          userType:'999',
          userParentId:'',
        },
      }
    },
    //enter=》登录
    created(){
      const that = this;
      document.onkeydown = (e)=>{
        let key = window.event.keyCode;
        if(key === 13){
          that.loginIn();
        }
      }
    },
    destroyed(){
      document.onkeydown = (e) =>{}
    },
    mounted(){
      // console.log(JSON.parse(window.localStorage.getItem('msgs')));
    },
    methods:{
      //限制手机号
      inputPhone(e){
        this.userData.phone = e.target.value.replace(/[^\d]/g,'');
      },
      //离开联系方式
      inPhones(){
        if(this.userData.phone.length!==7 && this.userData.phone.length!==11){
          this.$message.error('电话号码位数不对，请重新输入');
          this.userData.phone ='';
        }
      },
      //限制身份证号
      inputIdcard(e){
        this.userData.idCard = e.target.value.replace(/[^a-zA-Z\d]/g,'');
      },
      //身份证号验证性别
      inCardMessage(){
        let reg = /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
        if(reg.test(this.userData.idCard) === true){
          if(parseInt(this.userData.idCard.substr(16,1))%2 === 0){
            this.userData.gender ="1";
          }else {
            this.userData.gender ="0";
          }
        }else {
          this.$message.error('身份证格式不对，请重新输入');
          this.userData.idCard='';
        }
      },

      //图头像
      uplodPic(e){
        const that=this;
        let files = e.file.originFileObj;
        let size = e.file.size;
        if(size < 1024*1024){
          pic2Base64(files).then(function (result) {
            that.userData.userImg = result;
          });
        }else {
          if(that.isMessCount === 1){
            that.isMessError = that.$message.error('图片大小不能大于1M')
          }
          if(that.isMessCount === 3){
            that.isMessCount = 0;
          }
        }
        that.isMessCount++;

      },
      //展示数据字典中树的递归函数(弹出框设备类型)
      dataTreeDgData(pt, tree) {
        const that = this;
        let newRR = [];
        for (let t of tree) {
          if (pt.id === t.armyParentId) {
            let ct = that.dataTreeDgData(t, tree);
            if (ct.length !== 0) {
              newRR.push({
                title: t.armyName,
                children: ct,
                key: t.id,
                value: t.id,
                type: 'fatherNode',
              });
            } else {
              newRR.push({
                title: t.armyName,
                key: t.id,
                value: t.id,
                type: 'childNode',
              });
            }
          }
        }
        return newRR;
      },
      //注册 树选择
      onData() {
        const that = this;
        that.$apollo.query({
          query: require('../graphql/army/query/findAllArmy.gql'),
          variables: {},
          fetchPolicy: 'no-cache'
        }).then(data => {
          const equipmentTree = data.data.findAllArmy;
          const newTree = [];
          for (let r of equipmentTree) {
            if (r.armyParentId === '999') {
              let ct = that.dataTreeDgData(r, equipmentTree);
              if (ct.length !== 0) {
                newTree.push({
                  title: r.armyName,
                  key: r.id,
                  value: r.id,
                  children: that.dataTreeDgData(r, equipmentTree),
                  type: 'fatherNode',
                })
              } else {
                newTree.push({
                  title: r.armyName,
                  key: r.id,
                  value: r.id,
                  type: 'childNode',
                })
              }
            }
          }
          that.armyTypesDatas = [{
            title: '建制总览',
            key: '999',
            value:'999',
            children: newTree
          }];
        }).catch(error => {
          console.log(error);
        })
      },
      //编制上级
      onSelect(value,node,extra){
        this.values=node.title;
        this.userData.userParentId = value;
      },
      //人员注册确认
      addPersonnel() {
        const that = this;
        if(that.userData.name === ""){
          that.$message.error('未填写账户名！');
          return;
        }
        if(that.userData.code === ""){
          that.$message.error('未填写编号！');
          return;
        }
        if(that.userData.userParentId === ""){
          that.$message.error('未选择上级建制！');
          return;
        }
        if(that.userData.armyType === ""||that.userData.armyType === "999"){
          that.$message.error('未选择用户类别！');
          return;
        }
        if(that.userData.userType === ""||that.userData.userType === "999"){
          that.$message.error('未选择身份类别！');
          return;
        }
        if(that.userData.idCard === ""){
          that.$message.error('未输入身份证号！');
          return;
        }
        that.loadings = true;
        that.userData.gender = parseInt(that.userData.gender);
        that.$apollo.mutate({
          mutation:require('../graphql/army/mutation/saveUser.gql'),
          variables:{entity:that.userData},
        }).then((data)=>{
          that.$message.success("注册提交成功,请等待管理员审核！");
          that.handleReset();
          setTimeout(() => {
            that.modalPersonnel = false;
            that.loadings = false;
          }, 200);
        }).catch(error=>{
          console.log(error);
        })

      },
      //人员弹框重置按钮
      handleReset() {
        setTimeout(()=>{
          this.footers = this.slot;
        },200)
        this.userData={
          name:'',
          armyType:'999',
          code:'',
          gender:'0',
          idCard:'',
          password:'',
          phone:'',
          // userImg:'',
          userImg:'',
          remark:'0',
          userType:'999',
          userParentId:'',
        }
      },
      //人员弹框右上角X按钮
      cancelPersonnel(e) {
        this.modalPersonnel = false;
        setTimeout(()=>{
          this.handleReset();
        },200)
      },
      //登录
      loginIn(){
        const that = this;
        if(that.code === ""){
          that.$message.error("请输入账号！");
          return;
        }
        if(that.password === ""){
          that.$message.error("请输入密码！");
          return;
        }
        that.$apollo.query({
          query:require('../graphql/loginUser.gql'),
          variables:{code:that.code,password:that.password},
          fetchPolicy:'no-cache'
        }).then((data)=>{
          const loginUser = data.data.loginUser
          if(loginUser.code === "CODE_200"){
            if(loginUser.data.remark === "1"){
              let msg={
                id:loginUser.data.id,
                type:loginUser.data.armyType.toString()
              }
              // window.localStorage.setItem('msgs', JSON.stringify(msg));
              //vuex和localstrong配合使用存登录用户信息
              that.$store.dispatch('setUser',JSON.stringify(msg))
              that.routerSkip('/home');
              setTimeout(()=>{
                that.$message.success('登录成功！')
              },200)
            }else {
              that.$message.error("账户未审核，等待管理员审核！")
            }
          }else {
            that.$message.error(loginUser.message);
          }
        }).catch((error)=>{
          console.log(error)
        })
      },
      registerR(){
        this.onData();
        this.modalPersonnel = true;
      }
    }
  }
</script>
<style scoped>
  .LoginDIV{
    width: 481px;
    height: 360px;
    /*background: #aa99ba;*/
    background: linear-gradient(0deg,rgba(255,255,255,0.1)0%,rgba(255,255,255,0.12)84%,rgba(255,255,255,0.4)100%);
    z-index: 999;
  }
  .LoginDIV-01{
    border: 1px solid;
    background: linear-gradient(0deg,rgba(255,255,255,0.1)0%,rgba(255,255,255,0.12)84%,rgba(255,255,255,0.4)100%);
    border-image: linear-gradient(0deg,rgba(47,47,47,0.8),rgba(198,198,198,0.05),rgba(47,47,47,0.81)) 1 1;
    margin: 0 40px 0;
  }
  .LoginDIV-02{
    width: 380px;
    height: 240px;
    margin: 10px;
    padding: 30px;
    /*background: rgba(28,59,43,1);*/
    background: rgba(28,59,43,1);
    border: 1px solid;
    border-image:  linear-gradient(0deg,rgba(64,64,46,1),rgba(240,240,240,0)) 1 1;
  }
  .marIn{
    /*margin: 10px;*/
    /*background: #235C46 !important;*/
    border: none!important;
    width: 320px;
    height: 40px;
    margin-top: 20px;
  }
  .LoginButton{
    width: 320px;
    height: 40px;
    background: #235C46!important;
    border: none!important;
    margin-top: 20px;
  }
  .lizi{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 1;
    /*width: 100%;*/
    /*height: 100%;*/
    /*background: #1890FF;*/
  }
  .lizi01{
     position: fixed;
     top: 0;
     left: 0;
     right: 0;
     bottom: 0;
     z-index: 2;
   }
  .bttn{
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: 2;
  }
</style>
